package com.ubhave.powertracker;

import java.util.Calendar;
import java.util.Date;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

//SharedPreferences Changes Listener class
public class PowerTrackerSharedPreferenceChangeListener implements SharedPreferences.OnSharedPreferenceChangeListener{

	SharedPreferences settings;
	SharedPreferences.Editor editor;
	LifeGuideConnector lgc;
	
	String usr;
	String intervention;
	
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		
				
		settings =PreferenceManager.getDefaultSharedPreferences(PowerTrackerApplication.getContext());
        editor = settings.edit();
        lgc = new LifeGuideConnector(settings);
		
        //class detects changes to LifeGuideUser (for syncing logs and start dates), and QuestionnaireReminder (for setting the alarm).
		if(key.equals("LifeGuideUser")){
			String newUN = settings.getString("LifeGuideUser", "");
			
			if(newUN.contains(" ")){
				newUN = newUN.replaceAll("\\s", "");
				Toast.makeText(PowerTrackerApplication.getContext(), "Illegal whitespace in username, trimming", Toast.LENGTH_SHORT).show();
				editor.putString("LifeGuideUser", newUN);
				editor.commit();
			}
			
			//Log.i("POWeR Tracker: ", "UName Changed: "+settings.getString("LifeGuideUser", ""));
			
			class AsyncGetLogs extends AsyncTask{

        			@Override
        			protected Object doInBackground(Object... params) {
        				
        				usr = settings.getString("LifeGuideUser", "");
        				//Shouldn't need to re-initialise lgc and intervention but some how this Async task keeps launching before they've been initialised. This is messy but will do for now.
        				lgc = new LifeGuideConnector(settings);
        				intervention = settings.getString("LifeGuideInterventionId", "");
        				
        				Log.i("POWeR Tracker Special: ", "UNC "+usr);
        				//You changed user - lets check to see if you have existing log and start time data ...
        				try{
        					int logIterator=0;
        					while(true){
	        					String serverLog = lgc.getVar(intervention, usr, "user", "appUsageLog"+logIterator,settings.getString("authkey",""));
	        					//Log.i("POWeR Tracker Special: ", "UNC SL "+serverLog);
	        					if(serverLog!=null){
	    							editor.putString("usageLog"+logIterator, serverLog);
	    							editor.commit();
	    							logIterator++;
	    						}
	        					else
	        						break;
        					}
        					
        					logIterator=0;
    					
        					while(true){
	    						String serverSensorLog = lgc.getVar(intervention, usr, "user", "appSensorLog"+logIterator,settings.getString("authkey",""));
	    						//Log.i("POWeR Tracker Special: ", "UNC SSL "+serverSensorLog);
	    						if(serverSensorLog!=null){
	    							editor.putString("sensorLog"+logIterator, serverSensorLog);
	    							editor.commit();
	    							logIterator++;
	    						}
	    						else
	    							break;
        					}
        				
    						String serverAppStart = lgc.getVar(intervention, usr, "user", "appStart",settings.getString("authkey",""));
    						if(serverAppStart!=null&&!serverAppStart.equals("")){
    							editor.putString("appStart", serverAppStart);
    							editor.commit();
    						}
    						else{
    							if(settings.getString("appStart", "").equals("")){
    								editor.putString("appStart", new Date().getDate()+"-"+new Date().getMonth()+"-"+new Date().getYear());
    					            editor.commit();
    					            Log.i("POWeR Tracker: ","set appStart "+new Date().getDate()+"-"+new Date().getMonth()+"-"+new Date().getYear());
    							}
    							lgc.postVar(intervention, usr, "user", "appStart", settings.getString("appStart", ""),settings.getString("authkey",""));
    							
    						}
    						
    						String currentPhone = lgc.getVar(intervention, usr, "user", "currentPhone",settings.getString("authkey",""));
    						editor.putString("currentPhone", currentPhone);
				            editor.commit();
    						if(!settings.getString("currentPhone", "").equals(Build.MANUFACTURER+"-"+Build.MODEL)){
    							if(!usr.equals("")&&!intervention.equals("")){
    								editor.putString("currentPhone", Build.MANUFACTURER+"-"+Build.MODEL);
    								editor.putString("sensorLog", settings.getString("sensorLog", "")+"Push Sensor: ChangePhone("+Build.MANUFACTURER+"-"+Build.MODEL+") "+"TimeStamp("+new Date()+"), ");
    								editor.commit();
    								lgc.postVar(intervention, usr, "user", "currentPhone", settings.getString("currentPhone", ""),settings.getString("authkey",""));
    							}
    						}
    						
    						
    						String interventionMode = lgc.getVar(intervention, usr, "user", "interventionMode",settings.getString("authkey",""));
    						//Log.i("POWeR Tracker Special: ", "UNC IM! "+interventionMode);
    						if(interventionMode!=null&&!interventionMode.equals("")){
    							editor.putString("interventionMode", interventionMode);
    							editor.commit();
    							Log.i("POWeR Tracker Special: ", "IM "+interventionMode);
    						}
    						else{
    							editor.putString("interventionMode", "2");
    							editor.commit();
    							Log.i("POWeR Tracker Special: ", "IM null "+2);
    						}
    						
    						//This is a bit of a hack - if the app has changed user we need to reload the main page incase interventionMode has also changed, however in order to prevent multiple login boxes appearing when the app changes users Preferences sets UN to blank. We don't want to trigger a goto home on this blank UN.
    						if(usr!=""){
    							//Log.i("POWeR Tracker Special: ", "SPC goHome "+usr);
    							goHome();
    						}
    						
        				} catch (PowerTrackerInvalidAuthKeyException e) {
        					invalidKey();
        				}
    					
        				return null;
        				
        			}
			 };
			
			 new AsyncGetLogs().execute(this);
			 
		}
		
		if(key.equals("LifeGuideURL")||key.equals("LifeGuideInterventionId")){
			editor.remove("authkey");
			editor.remove("LifeGuideUser");
			editor.commit();
			goHome();
		}
		
		else if(key.equals("questionnaireNotificationTime")){
			
			AlarmManager alarmManager = (AlarmManager)PowerTrackerApplication.getContext().getSystemService(PowerTrackerApplication.getContext().ALARM_SERVICE);
		    String[] selectedTime = settings.getString("questionnaireNotificationTime", "").split(":");
		      
		    Intent myIntent = new Intent(PowerTrackerApplication.getContext() , DailyQuestionnaireReminderNotification.class);     
		      
		    PendingIntent pendingIntent = PendingIntent.getService(PowerTrackerApplication.getContext(), 0, myIntent, 0);
		     
		    Calendar calendar = Calendar.getInstance();
		    calendar.set(Calendar.HOUR_OF_DAY, new Integer(selectedTime[0]));
		    calendar.set(Calendar.MINUTE, new Integer(selectedTime[1]));
		    calendar.set(Calendar.SECOND, 00);
		      
		    Calendar current = Calendar.getInstance();
		    if(calendar.before(current)){
		    	calendar.setTimeInMillis(calendar.getTimeInMillis()+(24*60*60*1000));
		    }
		          
		    long interval = 24*60*60*1000;
		      if(settings.getBoolean("AlarmDebugModeOn", false))
		    	  interval=2*60*1000;
		      
		    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), interval , pendingIntent);  //set repeating every 24 hours
		    
		    Log.i("POWeR Tracker Special:", "Set Daily Questionnaire Alarm: "+calendar.getTimeInMillis());
		}
	}
	
	public void goHome(){
    	Intent intent = new Intent(PowerTrackerApplication.getContext(), PowerTrackerActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PowerTrackerApplication.getContext().startActivity(intent);
    }
	
	public void invalidKey(){
		//goHome();
	}
	
}